package com.openspring.framework.extend.spring;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.openspring.framework.exception.MessageAdapter;
import com.openspring.framework.util.JacksonUtils;

public class CustomMappingExceptionResolver extends SimpleMappingExceptionResolver {
	
	private static Logger logger = Logger.getLogger(CustomMappingExceptionResolver.class);
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex){
		ex.printStackTrace();
		// Expose ModelAndView for chosen error view.
		String viewName = determineViewName(ex, request);
		if (viewName != null) {
			String contentType = request.getContentType();
			String jsonHeader = request.getHeader("accept");
			String xmlHeader = request.getHeader("X-Requested-With");
			if(!((jsonHeader != null && jsonHeader.indexOf("application/json") > -1) || (xmlHeader != null && xmlHeader.indexOf("XMLHttpRequest") > -1)
					|| (contentType!= null && contentType.indexOf("multipart/form-data") > -1))) {
				// Apply HTTP status code for error views, if specified.
				// Only apply it if we're processing a top-level request.
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				return getModelAndView(viewName, ex, request);
			} else {//JSON格式返回 
				if(logger.isDebugEnabled())
					logger.debug("ajax request");
		        Map<String, Object> model=new HashMap<String, Object>();
		        String message = MessageAdapter.getMessage(ex);
		        if(message == null) {
		        	message = "未知错误,请联系管理员";
		        }
		        model.put("message", message);
		        model.put("success", false);
		        response.setContentType("text/html;application/json;charset=" + request.getCharacterEncoding());
		        try {
					JacksonUtils.writerJson(response.getWriter(), model);
				} catch (IOException e) {
					e.printStackTrace();
				}
		        return new ModelAndView();
			}
	    } else {
			return null;
	    }
	}
	
}
